package com.example.jwtdemo.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.util.StringUtils;

import java.security.SignatureException;
import java.util.Calendar;
import java.util.Map;
import java.util.UUID;

/**
 * @author Woo_home
 * @create 2020/9/13 18:48
 */

public class JwtUtil {

    /**
     * 私钥
     */
    private static final String SALT = UUID.randomUUID().toString().replace("-", "");

    /**
     * 生成 token header.payload.sing
     * @param map
     * @return
     */
    public static String generToken(Map<String, String> map) {
        Calendar instance = Calendar.getInstance();
        // 默认 7 天过期
        instance.add(Calendar.DATE, 7);
        // 创建 JWT builder
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });
        // 指定令牌过期时间
        String token = builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SALT));

        return token;
    }

    /**
     * 验证 token 合法性
     * @param token
     */
    public static DecodedJWT verify(String token) {
        if (!StringUtils.isEmpty(token)) {
            return JWT.require(Algorithm.HMAC256(SALT)).build().verify(token);
        }
        return null;
    }

    /**
     * 获取 token 信息
     * @param token
     * @return
     */
    public static DecodedJWT getTokenInfo(String token) {
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SALT)).build().verify(token);
        return verify;
    }
}
